package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.atguigu.tingshu.vo.base.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.DeleteMediaRequest;
import com.tencentcloudapi.vod.v20180717.models.DeleteMediaResponse;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

	@Autowired
	private TrackInfoMapper trackInfoMapper;
	@Resource
	AlbumInfoService albumInfoService;
	@Resource
	AlbumInfoMapper albumInfoMapper;
	@Resource
	TrackStatMapper trackStatMapper;
	@Resource
	VodService vodService;

	/**
	 * track_info 声音信息表
	 *
	 * ​     	user_id order_num media_duration media_size media_type source status 需要手动设置数据
	 *
	 * ​	user_id : 直接从工具类中获取
	 *
	 * ​	order_num :  声音在专辑中的排序值，从1开始依次递增，值越小排序越前，根据专辑Id上一条声音的排序值 并且按照声音Id 进行降序排列 并且获取第一条数.
	 *
	 * ​	media_duration media_size：根据流媒体Id获取到数据并赋值！
	 *
	 * ​	source status : 自己设置
	 *
	 * track_stat 声音统计表
	 *
	 * album_info 专辑表
	 * @param trackInfoVo
	 * @param userId
	 */
	@Override
	public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
		// 创建声音对象
		TrackInfo trackInfo = new TrackInfo();
		// 属性拷贝
		BeanUtils.copyProperties(trackInfoVo,trackInfo);
		trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
//		trackInfo.setUserId(1L);
		trackInfo.setUserId(userId);
		// 获取媒体信息.
		TrackMediaInfoVo trackMediaInfo = vodService.getTrackMediaInfo(trackInfoVo.getMediaFileId());

		trackInfo.setMediaSize(trackMediaInfo.getSize());
		trackInfo.setMediaUrl(trackMediaInfo.getMediaUrl());
		trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfo.getDuration()));
		trackInfo.setMediaType(trackMediaInfo.getType());
		// 获取上一条声音
		TrackInfo preTrackInfo = this.getOne(new LambdaQueryWrapper<TrackInfo>().eq(TrackInfo::getAlbumId, trackInfoVo.getAlbumId()).orderByDesc(TrackInfo::getId).select(TrackInfo::getOrderNum).last("limit 1"));
		int orderNum = 1;
		if(null != preTrackInfo) {
			orderNum = preTrackInfo.getOrderNum() + 1;
		}
		trackInfo.setOrderNum(orderNum);

		this.save(trackInfo);
		//更新专辑声音总数
		AlbumInfo albumInfo = albumInfoService.getById(trackInfo.getAlbumId());
		int includeTrackCount = albumInfo.getIncludeTrackCount() + 1;
		albumInfo.setIncludeTrackCount(includeTrackCount);
		albumInfoService.updateById(albumInfo);

		// 初始化统计数据
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_PLAY);
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_COLLECT);
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_PRAISE);
		this.saveTrackStat(trackInfo.getId(),SystemConstant.TRACK_STAT_COMMENT);
	}

	/**
	 * @Schema(description = "专辑id")
	 * 	private Long albumId;
	 *
	 *        @Schema(description = "标题")
	 * 	private String albumTitle;
	 *
	 *    @Schema(description = "声音id")
	 * 	private Long trackId;
	 *
	 *    @Schema(description = "标题")
	 * 	private String trackTitle;
	 *
	 *    @Schema(description = "专辑封面原图，尺寸不固定，最大尺寸为960*960（像素）")
	 * 	private String coverUrl;
	 *
	 *    @Schema(description = "声音媒体时长，单位秒")
	 * 	private BigDecimal mediaDuration;
	 *
	 *    @Schema(description = "状态")
	 *
	 *    @Schema(description = "播放量")
	 * 	private Integer playStatNum;
	 *
	 *        @Schema(description = "订阅量")
	 * 	private Integer collectStatNum;
	 *
	 *    @Schema(description = "点赞量")
	 * 	private Integer praiseStatNum;
	 *
	 *    @Schema(description = "评论数")
	 * 	private Integer commentStatNum;
	 * 	private String status;
	 * @param page
	 * @param limit
	 * @param trackInfoQuery
	 * @return
	 */
	@Override
	public PageVo<TrackListVo> findUserTrackPage(Long page, Long limit, TrackInfoQuery trackInfoQuery) {
		Page<TrackInfo> trackInfoPage=new Page<>(page,limit);
		trackInfoMapper.selectPage(trackInfoPage,new LambdaQueryWrapper<TrackInfo>().eq(StringUtils.hasLength(trackInfoQuery.getTrackTitle()),TrackInfo::getTrackTitle,trackInfoQuery.getTrackTitle()).eq(StringUtils.hasLength(trackInfoQuery.getStatus()),TrackInfo::getStatus,trackInfoQuery.getStatus()).eq(trackInfoQuery.getUserId()!=null,TrackInfo::getUserId,trackInfoQuery.getUserId()));
		List<TrackInfo> trackInfoList = trackInfoPage.getRecords();
		List<TrackListVo> list=new ArrayList<>();
		trackInfoList.stream().forEach(trackInfo -> {
			TrackListVo trackListVo=new TrackListVo();
			trackListVo.setAlbumId(trackInfo.getAlbumId());
			AlbumInfo albumInfo = albumInfoMapper.selectOne(new LambdaQueryWrapper<AlbumInfo>().eq(AlbumInfo::getId, trackInfo.getAlbumId()));
			trackListVo.setAlbumTitle(albumInfo.getAlbumTitle());
			trackListVo.setTrackId(trackInfo.getId());
			trackListVo.setTrackTitle(trackInfo.getTrackTitle());
			trackListVo.setCoverUrl(trackInfo.getCoverUrl());
			trackListVo.setMediaDuration(trackInfo.getMediaDuration());
			trackListVo.setStatus(trackInfo.getStatus());
			//
			Integer playStatNum = this.selectTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PLAY);
			Integer collectStatNum = this.selectTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COLLECT);
			Integer praiseStatNum = this.selectTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PRAISE);
			Integer commentStatNum = this.selectTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COMMENT);
			//@Schema(description = "播放量")
			//	private Integer playStatNum;
			//
			trackListVo.setPlayStatNum(playStatNum);
			//	@Schema(description = "订阅量")
			//	private Integer collectStatNum;
			//
			trackListVo.setCollectStatNum(collectStatNum);
			//	@Schema(description = "点赞量")
			//	private Integer praiseStatNum;
			//
			trackListVo.setPraiseStatNum(praiseStatNum);
			//	@Schema(description = "评论数")
			//	private Integer commentStatNum;
			trackListVo.setCommentStatNum(commentStatNum);
			list.add(trackListVo);
		});
		PageVo<TrackListVo> pageVo=new PageVo<>(list,trackInfoPage);
		return pageVo;
	}

	/**
	 * 传递声音Id ，封装好的TrackInfoVo 实体类。
	 * @param id
	 * @param trackInfoVo
	 */
	@Override
	public void updateTrackInfo(Long id, TrackInfoVo trackInfoVo) {
		TrackInfo trackInfo = this.getById(id);
		BeanUtils.copyProperties(trackInfoVo,trackInfo);
		if (!trackInfoVo.getMediaFileId().equals(trackInfo.getMediaFileId())) {
			//	说明已经修改过了.
			TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(trackInfoVo.getMediaFileId());
			//	判断对象不为空.
			if (null==trackMediaInfoVo){
				//	抛出异常
				throw new GuiguException(ResultCodeEnum.VOD_FILE_ID_ERROR);
			}
			trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
			trackInfo.setMediaType(trackMediaInfoVo.getType());
			trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfoVo.getDuration()));
			trackInfo.setMediaSize(trackMediaInfoVo.getSize());
		}
		trackInfoMapper.updateById(trackInfo);
	}

	/**
	 * 涉计的表： track_info，album_info，track_stat，media
	 * @param id
	 */
	@Override
	public void removeTrackInfo(Long id) {
		TrackInfo trackInfo = trackInfoMapper.selectById(id);
		trackInfoMapper.deleteById(id);
		//更新专辑声音总数
		AlbumInfo albumInfo = this.albumInfoService.getById(trackInfo.getAlbumId());
		int includeTrackCount = albumInfo.getIncludeTrackCount() - 1;
		albumInfo.setIncludeTrackCount(includeTrackCount);
		albumInfoService.updateById(albumInfo);

		//删除统计数据
		trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, id));

		//删除声音媒体
		vodService.removeTrack(trackInfo.getMediaFileId());
	}

	private void saveTrackStat(Long trackId, String trackType) {
		TrackStat trackStat = new TrackStat();
		trackStat.setTrackId(trackId);
		trackStat.setStatType(trackType);
		trackStat.setStatNum(0);
		this.trackStatMapper.insert(trackStat);
	}
	public Integer selectTrackStat(Long trackId,String statType){
		QueryWrapper<TrackStat> queryWrapper=new QueryWrapper<>();
//		queryWrapper.select("stat_num");
		queryWrapper.eq("track_id",trackId);
		queryWrapper.eq("stat_type",statType);
		TrackStat trackStat = trackStatMapper.selectOne(queryWrapper);
		return trackStat.getStatNum();
	}


}

